package com.ericsson.enap.modules.cdr.thread;

import com.ericsson.common.pojo.FTPInfoVO;
import com.ericsson.common.util.FtpCarrierUtil;
import com.ericsson.common.util.LogFileName;
import com.ericsson.common.util.LoggerUtils;
import com.ericsson.enap.modules.cdr.entity.CdrCg;
import com.ericsson.enap.modules.cdr.mapper.CdrCgMapper;
import com.ericsson.common.pojo.CdrDownVo;
import org.slf4j.Logger;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 下载IMSCDR线程（根据IMSCG划分）
 */
public class IMSCGCDRDownLoadThread implements Runnable{

    private static Logger log = LoggerUtils.Logger(LogFileName.ImsCdrDownLoadJob);
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    private FTPInfoVO ftpInfo;
    // 下载的文件修改时间，用于作为下次下载的时间标志
    private Long loadFileModifyTime;

    private Long timeAndNum;
    private CdrDownVo cdrDownVoLast = new CdrDownVo();
    private String imsDownloadDir;
    private String imscdrDownloadInterval;
    private CdrCgMapper cdrCgMapper;

    public IMSCGCDRDownLoadThread(FTPInfoVO ftpInfo, Long loadFileModifyTime, Long timeAndNum, String fileName, String imsDownloadDir, String imscdrDownloadInterval, CdrCgMapper cdrCgMapper) {
        this.ftpInfo = ftpInfo;
        this.loadFileModifyTime = loadFileModifyTime;
        this.timeAndNum = timeAndNum;
        this.cdrDownVoLast.setLoadFileModifyTime(loadFileModifyTime);
        if(fileName != null && !fileName.equals("null")){
            this.cdrDownVoLast.setFileName(fileName);
        }
        this.cdrDownVoLast.setTimeAndNum(timeAndNum);
        this.imsDownloadDir=imsDownloadDir;
        this.imscdrDownloadInterval=imscdrDownloadInterval;
        this.cdrCgMapper=cdrCgMapper;
    }
    @Override
    public void run() {
        String dirpath = ftpInfo.getPath();
        log.info("begin start-----------------------" + " dirpath :" + dirpath + "---------------------");

        FtpCarrierUtil ftpCarrier = new FtpCarrierUtil(ftpInfo,log/*,downLoadFileLog*/);
        try {
            ftpCarrier.connect();
        } catch (Exception e1) {
            log.info("CDRDownLoadTask>>FTP connect error ================== "
                    + e1.getMessage());
        }
        long nowTime = System.currentTimeMillis();
        Date nowDate = new Date(nowTime);
        long beforeTime;
        Date beforeDate = null;
        if (loadFileModifyTime == null || (nowTime - loadFileModifyTime) > 2*60*60*1000) { // 当数据库中最后时间为空或与当前时间相差两小时以上时，说明系统中断，按第一次下载
            int timeIn = 0;
            try {
                // 获取系统设定的初始下载时间差
                timeIn = Integer.parseInt(imscdrDownloadInterval);
            } catch (Exception e) {
                log.info("CDRDownLoadTask类>>系统设置的初始化下载时间差不正确，请查看collector_cdrdownload.properties文件中的cdrJobInterval参数");
            }
            beforeTime = nowTime - timeIn * 60000L;
            //首次下载设置时间和序号
            Calendar c = Calendar.getInstance();
            c.add(Calendar.MINUTE, -timeIn);//当前时间之前减去cdrJobInterval的分钟数
            cdrDownVoLast.setTimeAndNum(0);
            //防止时间设置过短，导致未下载到文件时出现时间为0的情况
            cdrDownVoLast.setLoadFileModifyTime(c.getTimeInMillis());

        } else {
            beforeTime = loadFileModifyTime;
        }

        beforeDate = new Date(beforeTime);
        log.info("formatter.format(nowDate) :" +formatter.format(nowDate) + " formatter.format(beforeDate)) :" +formatter.format(beforeDate) + " dirpath :" + dirpath);
        // 判断是否是同一天
        if (formatter.format(nowDate).equals(formatter.format(beforeDate))) {
            // 是同一天
            log.info("sameday " + " dirpath :" + dirpath);
            cdrDownVoLast = ftpCarrier.download_IMSCDR(imsDownloadDir+File.separator, formatter.format(beforeDate),cdrDownVoLast);
            //更新至数据库
            if(cdrDownVoLast != null){
                updateTimeMillis(cdrDownVoLast.getLoadFileModifyTime(),cdrDownVoLast.getTimeAndNum(),cdrDownVoLast.getFileName(),ftpInfo.getCdrPathId());
            }
        } else {
            log.info("===== different day =====" + " dirpath :" + dirpath);
            // 不是同一天
            cdrDownVoLast = ftpCarrier.download_IMSCDR(imsDownloadDir+File.separator, formatter.format(beforeDate),cdrDownVoLast);
            log.info("===== different day before day time=====" + loadFileModifyTime + " dirpath :" + dirpath);
            Date before = new Date(loadFileModifyTime);
            log.info("===== different day before day date =====" + before + " dirpath :" + dirpath);
            log.info("===== different day nowTime=====" + nowTime + " dirpath :" + dirpath);
            Date nowDate1 = new Date(nowTime);
            log.info("=====different day nowDate "+nowDate1 + " dirpath :" + dirpath);

            //设置标记时间为当天00:00:00时刻
            Calendar c = Calendar.getInstance();
            c.set(Calendar.HOUR_OF_DAY, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.SECOND, 0);
            long todayTime = c.getTime().getTime();
            if(cdrDownVoLast == null){
                cdrDownVoLast = new CdrDownVo();
                cdrDownVoLast.setLoadFileModifyTime(todayTime);
                cdrDownVoLast.setTimeAndNum(-1);
                log.info("===== Init again =====");
            }
            cdrDownVoLast = ftpCarrier.download_IMSCDR(imsDownloadDir+ File.separator,formatter.format(nowDate),cdrDownVoLast);
            //更新至数据库
            if(cdrDownVoLast != null){
                updateTimeMillis(cdrDownVoLast.getLoadFileModifyTime(),cdrDownVoLast.getTimeAndNum(),cdrDownVoLast.getFileName(),ftpInfo.getCdrPathId());
            }
            log.info("===== different day today ====="+todayTime +" dirpath :" + dirpath);
            Date today = new Date(todayTime);
            log.info("===== different day today date =========" + today +  " dirpath :" + dirpath);
        }
        try {
            ftpCarrier.close();
        } catch (IOException e) {
            log.error("CDRDownLoadTask close ftp connection IO Exception：" + e.getMessage() + " dirpath :" + dirpath);
        }
        log.info(" ===== CDRDownLoadTask execute  end============="  +" dirpath :" + dirpath);

        log.info("end stop-----------------------" + " dirpath :" + dirpath + "---------------------");
    }

    private void updateTimeMillis(long loadFileModifyTime, long timeAndNum, String fileName, long cdrPathId) {
        CdrCg cdrCg=new CdrCg();
        cdrCg.setLastFileModifyTime(String.valueOf(loadFileModifyTime));
        cdrCg.setTimeAndNum(String.valueOf(timeAndNum));
        cdrCg.setFileName(fileName);
        cdrCg.setId((int)(cdrPathId));
        cdrCgMapper.updateDownloadCon(cdrCg);
    }
}
